using iTextSharp.text.pdf;
using Pdf2epub.Model;
using System.Collections.Generic;

namespace Pdf2epub.BusinessLogic.Extractors
{
    internal class PdfOutlineExtraction
    {
        public Chapter[] Extract(PdfReader pdfReader)
        {
            IList<Dictionary<string, object>> bookmarks = SimpleBookmark.GetBookmark(pdfReader);

            return ProcessChapterBookmarks(bookmarks, null);
        }

        private static string ExtractBookmarkField(Dictionary<string, object> bookmark, string fieldName)
        {
            if (!bookmark.ContainsKey(fieldName))
                return string.Empty;

            return bookmark[fieldName] as string;
        }

        private IEnumerable<Dictionary<string, object>> ExtractChildChapters(Dictionary<string, object> bookmark)
        {
            if (!bookmark.ContainsKey("Kids"))
                return null;

            return bookmark["Kids"] as List<Dictionary<string, object>>;
        }

        private Chapter[] ProcessChapterBookmarks(IEnumerable<Dictionary<string, object>> bookmarks, Chapter parentChapter)
        {
            List<Chapter> result = new List<Chapter>();
            foreach (var bookmark in bookmarks)
            {
                string title = ExtractBookmarkField(bookmark, "Title");
                string page = ExtractBookmarkField(bookmark, "Page");
                string named = ExtractBookmarkField(bookmark, "Named");

                Chapter chapter = new Chapter(parentChapter, title);

                IEnumerable<Dictionary<string, object>> childChapters = ExtractChildChapters(bookmark);
                if (childChapters != null)
                {
                    chapter.SubChapters.AddRange(ProcessChapterBookmarks(childChapters, chapter));
                }

                result.Add(chapter);
            }
            return result.ToArray();
        }
    }
}